<template>
  <CommonPage show-footer>
    <div class="content" style="  overflow-x: hidden;">
      <!-- panel头部 -->
      <div class="panel-header-box">
        <div style="flex-grow: 1;font-weight: 600;font-size: 20px;display:flex;align-items: center">
          <n-dropdown :options="projectOptions" @select="handleProjectSelect">
            <NButton text>
              <template #icon>
                <i class="i-fe:menu" size="50" />
              </template>
              <span class="ml-10">{{ useProject.name }}</span>
            </NButton>
          </n-dropdown>
        </div>
        <div style="margin-right: 20px">
          <n-avatar-group :options="projectUsers" :size="30" :max="4" @click="showUserManager = true">
            <template #avatar="{ option: { name } }">
              <n-tooltip trigger="hover">
                <template #trigger>
                  <!-- 先显示名称的前一位 -->
                  <NAvatar
                    round
                    size="small"
                    style="background-color: #4c86f9;color: white"
                  >
                    <!--   {{ name.substr(0, 1).toUpperCase() }} -->
                    {{ name }}
                  </NAvatar>
                </template>
                {{ name }}
              </n-tooltip>
            </template>
            <!-- 溢出容器样式 -->
            <template #rest="{ options: restOptions, rest }">
              <n-dropdown :options="dropdownOptions(restOptions)" placement="top">
                <NAvatar>+{{ rest }}</NAvatar>
              </n-dropdown>
            </template>
          </n-avatar-group>
        </div>
        <div style="display: flex;align-items: center">
          <!-- 项目搜索 -->
          <!--          <n-tooltip trigger="hover"> -->
          <!--            <template #trigger> -->
          <!--              <NButton text> -->
          <!--                <template #icon> -->
          <!--                  <i class="i-fe:search" size="40" /> -->
          <!--                </template> -->
          <!--              </NButton> -->
          <!--            </template> -->
          <!--            功能开发中... -->
          <!--          </n-tooltip> -->
          <!-- 项目设置 -->
          <n-dropdown :options="moreOptions" @select="selectSetting">
            <NButton text style="margin-left: 10px">
              <template #icon>
                <i class="i-fe:settings" size="40" />
              </template>
            </NButton>
          </n-dropdown>
          <!-- 新建项目 -->
          <NButton text style="margin-left: 10px" @click="showCreatProject = true">
            <template #icon>
              <i class="i-fe:plus" size="60" />
            </template>
          </NButton>
        </div>

        <span class="mx-6 opacity-20">|</span>
        <div class="ml-auto flex flex-shrink-0 items-center px-12 text-18">
          <ToggleTheme />
          <Fullscreen />
          <UserAvatar />
        </div>
      </div>

      <n-divider />

      <div v-if="userStore.userInfo.lastProjectId == null">
        <n-result
          status="info"
          title="提示"
          description="您还没有创建项目，现在去创建项目"
        >
          <template #footer>
            <NButton type="primary" @click="showCreatProject = true">
              创建项目
            </NButton>
          </template>
        </n-result>
      </div>

      <div
        v-if="userStore.userInfo.lastProjectId != null && userStore.userInfo.lastProjectId > 0 "
        class="content-wrapper"
      >
        <view class="list_content">
          <view
            v-for="column in columnList"
            :key="column.id"
            ref="setColumnRef"
            :data-column-id="column.id"
            class="column-item"
            draggable="true"
            @dragstart="handleColumnDragStart($event, column)"
            @dragover.prevent="handleColumnDragOver($event, column)"
            @drop="handleColumnDrop($event, column)"
          >
            <view class="item" ref="itemRef">
              <view class="title-box">
                <span>{{ column.name }}</span>
                <n-dropdown :options="columnOptions" @select="(key, option) => selectColumnOption(key, option, column.id)">
                  <NButton text>
                    <template #icon>
                      <i class="i-fe:more-horizontal" />
                    </template>
                  </NButton>
                </n-dropdown>
              </view>
              <n-scrollbar class="item-list">
                <Task v-for="task in tasksForColumn(column.id)" :key="task.id" :task="task" :project-users="projectUsers" :flow-list="flowList" @click="handleCardItem(task, column)" @refresh="updateList" />
                <div class="add-card-box" @click="showAddTaskModal(column)">
                  <NButton text style="margin-left: 10px">
                    <template #icon>
                      <i class="i-fe:plus" size="60" />
                    </template>
                  </NButton>
                  <span>添加卡片</span>
                </div>
              </n-scrollbar>
            </view>
          </view>

          <!-- 新增列表 -->
          <div class="new-board-box">
            <NButton secondary strong class="new-board-btn" @click="showCreateColumn = true">
              <template #icon>
                <i class="i-fe:plus" />
              </template>
              新增列表
            </NButton>
          </div>
        </view>
      </div>
    </div>
  </CommonPage>

  <!-- 添加卡片 -->
  <n-modal v-model:show="showModal" preset="card" class="common-modal">
    <template #header>
      {{ selectColumn.name }}
    </template>
    <TaskAdd ref="addModalRef" :column-info="selectColumn" :project="useProject" @close-modal="closeTaskModal" />
  </n-modal>

  <!-- 卡片详情 -->
  <n-modal
    v-model:show="showDetailModal" preset="card" :data="selectedTask" class="common-modal"
    style="background-color: white"
  >
    <template #header>
      {{ selectColumn.name }}
    </template>

    <TaskDetail
      ref="detailModalRef" :task="selectedTask" :column-info="selectColumn" :project="useProject"
      @close-modal="closeDetailModal"
    />
  </n-modal>

  <!-- 成员管理 -->
  <n-modal v-model:show="showUserManager" preset="card" class="common-modal">
    <template #header>
      成员管理
    </template>

    <div style="display: flex; width: 100%;margin-top: 15px; align-items: center;">
      <span style="flex: none">⠀项目成员：</span>

      <n-select
        v-model:value="checkProjectUsers"
        multiple
        :options="orgUsers"
        :render-label="renderLabel"
        :render-tag="renderMultipleSelectTag"
      />
    </div>

    <n-space style="justify-content: right;align-items: center" class="mr-10 mt-15">
      <NButton>
        取消
      </NButton>
      <NButton type="primary" @click="saveUserManager">
        保存
      </NButton>
    </n-space>
  </n-modal>

  <!-- 新建项目 -->
  <n-modal v-model:show="showCreatProject" preset="card" class="common-modal" style="width: 360px">
    <template #header>
      新建项目
    </template>

    <div style="display: flex; width: 100%;margin-top: 15px; align-items: center;">
      <span style="flex: none">⠀项目名称：</span>
      <n-input
        v-model:value="project.name"
        placeholder="输入项目名称"
      />
    </div>

    <div style="display: flex; width: 100%;margin-top: 15px; align-items: flex-start;">
      <span style="flex: none;padding-top: 6px">⠀项目描述：</span>
      <n-input
        v-model:value="project.desc"
        type="textarea"
        placeholder="输入项目描述"
        :autosize="{
          minRows: 3,
          maxRows: 10
        }"
      />
    </div>

    <n-space style="justify-content: right;align-items: center" class="mr-10 mt-15">
      <NButton @click="showCreatProject = false">
        取消
      </NButton>
      <NButton type="primary" @click="addProject">
        保存
      </NButton>
    </n-space>
  </n-modal>

  <!-- 工作流设置 -->
  <n-modal v-model:show="showWorkflow" preset="card" class="common-modal">
    <template #header>
      <span>工作流设置</span>
    </template>

    <Flow style="background: #fff;" />
  </n-modal>

  <!-- 新建列表 -->
  <n-modal v-model:show="showCreateColumn" preset="card" class="common-modal">
    <template #header>
      新建列表
    </template>

    <div style="display: flex; width: 100%;margin-top: 15px; align-items: center;">
      <span style="flex: none">⠀列表名称：</span>
      <n-input
        v-model:value="createColumnName"
        placeholder="输入列表名称"
      />
    </div>

    <n-space style="justify-content: right;align-items: center" class="mr-10 mt-15">
      <NButton @click="showCreateColumn = false">
        取消
      </NButton>
      <NButton type="primary" @click="addColumn">
        保存
      </NButton>
    </n-space>
  </n-modal>
  <!-- 系统用户管理 -->
  <!-- 添加卡片 -->
  <n-modal v-model:show="showSysUserManager" preset="card" class="common-modal">
    <template #header>
      用户管理
    </template>
    <SysUserManager />
  </n-modal>
</template>

<script setup lang="ts">
import { CommonPage } from '@/components'
import { Fullscreen, UserAvatar } from '@/layouts/components'
import { useUserStore } from '@/store'
import { getUserInfo } from '@/store/helper'
import { lStorage } from '@/utils'
import Flow from '@/views/kanban/flow.vue'
import SysUserManager from '@/views/kanban/SysUserManager.vue'
import TaskAdd from '@/views/kanban/TaskAdd.vue'
import TaskDetail from '@/views/kanban/TaskDetail.vue'
import { monitorForElements,draggable,
  dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
import { triggerPostMoveFlash } from '@atlaskit/pragmatic-drag-and-drop-flourish/trigger-post-move-flash'
import {attachClosestEdge, extractClosestEdge} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'
import { reorderWithEdge } from '@atlaskit/pragmatic-drag-and-drop-hitbox/util/reorder-with-edge'
import { TrashOutline as DeleteIcon, SettingsSharp as SettingIcon, PersonCircleOutline as UserIcon, EyeSharp as VisIcon } from '@vicons/ionicons5'
import { NAvatar, NButton, NIcon, NTag, NText, type SelectRenderLabel, type SelectRenderTag } from 'naive-ui'
import { h, nextTick, onMounted, onUnmounted, ref } from 'vue'
import Task from '../kanban/task.vue'
import api from './api'
import {combine} from "@atlaskit/pragmatic-drag-and-drop/combine"

// 项目列表选项
const projectOptions = ref([
  {
    label: '我的项目',
    key: 'my-projects', 
    disabled: true
  },
  {
    type: 'divider',
    key: 'd1'
  }
])

// 项目切换处理
async function handleProjectSelect(key) {
  // 更新用户最后访问的项目ID
  userStore.userInfo.lastProjectId = key
  // 重新获取项目信息
  await getProject()
};

// 列表
const columnList = ref([])

// const columnRefs = ref([]) // 用于保存每个列的 DOM 引用

// 创建一个函数来设置 ref，并将其保存到响应式数组中
// function setColumnRef(el) {
//   if (el) {
//     const index = columnList.value.findIndex(col => col.id === el.getAttribute('data-column-id'))
//     if (index !== -1) {
//       columnRefs.value[index] = el
//     }
//   }
// }

//用于保存每个列的 DOM 引用
// const columnRefs = ref([]);



// 显示系统用户管理
const showSysUserManager = ref(false)

// 项目成员列表
const projectUsers = ref([])

// 平台所有人员列表
const orgUsers = ref([])

// 所有任务
const allTask = ref([])
// 当前显示的task
const tasks = ref([])
// 成员管理
const showUserManager = ref(false)
// 当前的项目id
const selectProjectId = ref('0')
const userStore = useUserStore()

// 工作流列表
const flowList = ref([])
// 选择的列表
const selectColumn = ref({})
// 卡片详情
const showDetailModal = ref(false)
// 添加卡片
const showModal = ref(false)

// 添加任务的确认或者按钮回调，确定按钮refresh为true
function updateList(refresh) {
  if (refresh) {
    getTaskList()
  }
}

function closeTaskModal(refresh) {
  showModal.value = false
  if (refresh) {
    getTaskList()
  }
}

function closeDetailModal(refresh) {
  showDetailModal.value = false
  if (refresh) {
    getTaskList()
  }
}

// 创建列表
const showCreateColumn = ref(false)

// 页面用的项目实体
const useProject = ref({
  id: 0,
  name: '',
  desc: '',
})

// 新建项目的实体
const project = ref({
  name: '',
  description: '',
})

const showCreatProject = ref(false)

function renderIcon(icon) {
  return () => {
    return h(NIcon, null, {
      default: () => h(icon),
    })
  }
}

const columnOptions = ref([
  {
    label: '删除列表',
    key: 'delete-column',
    icon: renderIcon(DeleteIcon),
  },
])

watch(showUserManager, (newVal) => {
  if (newVal) {
    fetchOrgUsers()
  }
})

// 获取组织所有人员信息，选择加入本项目
async function fetchOrgUsers() {
  const { data } = await api.getOrgUser()
  console.log(`用户列表返回-->${data}`)
  console.log(data)
  orgUsers.value = []
  orgUsers.value = data.list
  orgUsers.value.forEach((item) => { // 增加value字段
    item.value = item.id
  })

  // 这里话是什么意思
}

// 创建的列表名称
const createColumnName = ref('')

// 添加列表
async function addColumn() {
  if (!createColumnName.value) {
    $message.info('列表名称不能为空')
    return
  }
  const { data } = await api.addColumn(useProject.value.id, createColumnName.value)
  console.log(`添加列表返回-->${data}`)
  console.log(data)
  $message.success('列表创建成功')
  showCreateColumn.value = false
  createColumnName.value = '' // 清空
  getColumnList()
}

const showComple = ref(lStorage.get('ShowCompleted' === 'true'))
// 项目更多设置
const moreOptions = ref([
  // {
  //   label: '工作流',
  //   key: 'workflow',
  //   icon: renderIcon(EditIcon),
  // },
  {
    label: '项目设置',
    key: 'project-setting',
    icon: renderIcon(SettingIcon),
  },
  {
    // label: showComple?'显示已完成':'隐藏已完成',  //TODO 不生效，再考虑怎么处理
    label: '显示/隐藏已完成',
    key: 'show-completed',
    icon: renderIcon(VisIcon),
  },
  {
    label: '成员管理',
    key: 'users',
    icon: renderIcon(UserIcon),
  },
  // {
  //   label: '归档项目',
  //   key: 'logout',
  //   icon: renderIcon(LogoutIcon),
  // },
  // {
  //   label: '删除项目',
  //   key: 'logout',
  //   icon: renderIcon(LogoutIcon),
  // },
])

// 工作流
const showWorkflow = ref(false)

// 删除用户列表
async function deleteColumn(columnId) {
  const projectId = userStore.userInfo.lastProjectId
  const { data } = await api.deleteColumn(projectId, columnId)
  console.log(`删除列表返回-->${data}`)
  console.log(data)
  $message.success('列表删除成功')
  getColumnList() // 获取新的列表信息
  getTaskList() // 刷新任务列表
}

// 任务列表项下拉
function selectColumnOption(key, option, columnId) {
  console.log(`columnId----->${columnId}`)
  console.log(`option----->${option}`)
  switch (key) {
    case 'delete-column':
      console.log('click the delete column')
      $dialog.warning({
        title: '警告',
        content: '你确定删除列表，列表内任务将全部删除？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          deleteColumn(columnId)
        },
        onNegativeClick: () => {
        },
      })
      break
    default:
      break
  }
}

// 是否显示已完成，默认显示
function showCompleted(show) {
  showComple.value = show
  lStorage.set('ShowCompleted', show)
  // console.log("------------------------------>进来这里")
  if (show) {
    // console.log("------------------------------>进来这里1")
    tasks.value = []
    tasks.value = allTask.value
  }
  else {
    // console.log("------------------------------>进来这里2")
    tasks.value = []
    const incompleteTasks = allTask.value.filter(item => !item.completeTime)
    console.log('incompleteTasks value', incompleteTasks)
    tasks.value = incompleteTasks
  }
}
// 项目设置下拉选择
function selectSetting(key, option) {
  console.log(option)
  switch (key) {
    case 'workflow': // 工作流
      showWorkflow.value = true
      console.log(`showWorkflow点击key----------->showWorkflow${key}`)
      break
    case 'users':
      showUserManager.value = true
      console.log(`点击了成员管理`)
      break
    case 'project-setting':
      showCreatProject.value = true // 设置为编辑模式
      break
    case 'show-completed':
      showCompleted(!lStorage.get('ShowCompleted')) // 取反
      break
    default:
      console.log(`功能开发中...`)
      break
  }
}

async function refreshUserInfo() {
  const user = await getUserInfo()
  userStore.setUser(user)
}

// 创建项目
async function addProject() {
  const projectName = project.value.name.trim()
  console.log(`projectName-->${projectName}`)
  if (!projectName) {
    $message.info('项目名称不能为空')
    return
  }
  const { data } = await api.addProject(projectName, project.value.desc.trim(), 'open')
  console.log(`添加项目返回-->${data}`)
  console.log(data)
  // 处理data的数据
  $message.success('创建项目成功')
  showCreatProject.value = false
  project.value.name = ''
  project.value.description = ''
  refreshUserInfo() // 刷新用户信息，后台更新用户最后使用项目为当前项目id
  // 刷新当前页面等
}

function dropdownOptions(restOptions) {
  return restOptions.map(option => ({
    key: option.id,
    label: option.name,
  }))
}

// 设置拖拽监听的函数
let unsubscribe: (() => void) | null = null

// 当前选中的卡片
const selectedTask = ref(null)

const detailModalRef = ref(false)

const addModalRef = ref(false)

// 卡片点击事件
function handleCardItem(task, column) {
  selectedTask.value = task
  selectColumn.value = column
  showDetailModal.value = true
}

// 默认选中的项目成员（默认肯定全部选中）
const checkProjectUsers = ref([])

async function getProjectUserInfo(ids) {
  const { data } = await api.getBasic(ids.value)
  projectUsers.value = data
  projectUsers.value.forEach((item) => { // 增加value字段
    item.value = item.id
  })

  checkProjectUsers.value = projectUsers.value.reduce((acc, item) => {
    acc.push(item.id)
    return acc
  }, [])
  console.log(`checkProjectUsers-->${checkProjectUsers.value}`)
}

const ids = ref([])

// 监听 useProject 的变化
watch(useProject, (newValue) => {
  if (newValue) {
    // const projectId = newValue.id
    if (newValue && Array.isArray(newValue.project_user)) {
      // 使用 map 方法提取每个元素的 id
      ids.value = newValue.project_user.map(item => item.userid)
      // console.error(`ids is ${ids.value}`)
      getProjectUserInfo(ids)
    }
    getColumnList()
    getFlowList()
  }
})

// 拖拽事件设定
function setupDragAndDrop() {
  return monitorForElements({
    onDrop({ location, source }) {
      const target = location.current.dropTargets[0]
      if (!target)
        return
      const sourceData = source.data
      const targetData = target.data
      console.error('tasks-->', tasks)
      console.error('sourceData-->', sourceData)
      console.error('target.data-->', target.data)
      const indexOfSource = tasks.value.findIndex(task => task.id === sourceData.id)
      console.error(`indexOfSource-->${indexOfSource}`)
      const indexOfTarget = tasks.value.findIndex(task => task.id === targetData.id)
      console.error(`indexOfTarget-->${indexOfTarget}`)
      const closestEdgeOfTarget = extractClosestEdge(targetData)
      console.error(`closestEdgeOfTarget-->${closestEdgeOfTarget}`)

      // 检查源列名和目标列名是否不相等
      if (sourceData.columnId !== targetData.columnId) {
        // 更新源任务的 columnId 为目标列的 id
        tasks.value[indexOfSource].columnId = targetData.columnId
      }

      tasks.value = reorderWithEdge({
        list: tasks.value,
        startIndex: indexOfSource,
        indexOfTarget,
        closestEdgeOfTarget,
        axis: 'vertical',
      })

      // 这个是本地的排序
      nextTick(() => {
        const element = document.querySelector(`[data-task-id="${sourceData.taskId}"]`)
        if (element instanceof HTMLElement) {
          triggerPostMoveFlash(element)
        }
      })
    },
  })
}

// 请求项目信息
async function getProject() {
  const projectId = userStore.userInfo.lastProjectId
  const { data } = await api.getProject(projectId)
  useProject.value = data
  selectProjectId.value = projectId
}

// 请求列表信息
async function getColumnList() {
  const projectId = userStore.userInfo.lastProjectId
  const { data } = await api.getColumnList(projectId)
  columnList.value = data.data

  // setdrag()
}

// 请求工作流信息
async function getFlowList() {
  const projectId = userStore.userInfo.lastProjectId
  const { data } = await api.getFlowList(projectId)
  flowList.value = data[0].project_flow_item
}

// 请求任务列表
async function getTaskList() {
  const projectId = userStore.userInfo.lastProjectId
  const { data } = await api.getTaskList(projectId)
  allTask.value = []
  allTask.value = data.data
  showCompleted(lStorage.get('ShowCompleted'))
}


const state = ref({
  type: 'idle',
  container: null,
  closestEdge: null,
})

// const setColumnRef = ref ()


// function  setColumnRef(el, index) {
//   // 为列设置引用
//   this.$refs.columns = this.$refs.columns || [];
//   this.$refs.columns[index] = el;
// }

//const itemRef = ref(null)

// 创建一个函数来动态设置项的引用
const itemRefs = ref({});
const columnRefs = ref({});
// 创建一个方法来设置列的引用
const setColumnRef = (el) => {
  if (el) {
    // 将列的引用存储在 columnRefs 对象中
    columnRefs.value[el.getAttribute('data-column-id')] = el;
  }
};



function setdrag(){
  console.error("setdrag ---->")
  // 遍历所有的列并设置拖拽行为
  Object.keys(columnRefs.value).forEach((key) => {
    const columnEl = columnRefs.value[key];
    console.log("columnEl ---->"+columnEl)
    draggable({
      element: columnEl,
      getInitialData() {
        return { columnId: columnList.value.find(col => col.id === key).id };
      },
    });
  });



}

onMounted(() => {

  setdrag()
  // const element = setColumnRef.value
  // if (!element)
  //   return
  // combine(
  //     draggable({
  //       element,
  //       getInitialData() {
  //         // return getTaskData(props.task)
  //         return columnList
  //       },
  //     }),
  //     dropTargetForElements({
  //       element,
  //       canDrop({ source }) {
  //         if (source.element === element) {
  //           return false
  //         }
  //         return true
  //       },
  //       getData({ input }) {
  //         // const data = getTaskData(props.task)
  //         const data = columnList
  //         return attachClosestEdge(data, {
  //           element,
  //           input,
  //           allowedEdges: ['top', 'bottom'],
  //         })
  //       },
  //       getIsSticky() {
  //         return true
  //       },
  //       onDragEnter({ self }) {
  //         const closestEdge = extractClosestEdge(self.data)
  //         state.type = 'is-dragging-over'
  //         state.closestEdge = closestEdge
  //       },
  //       onDrag({ self }) {
  //         const closestEdge = extractClosestEdge(self.data)
  //         if (state.type === 'is-dragging-over' && state.closestEdge === closestEdge) {
  //           return
  //         }
  //         state.type = 'is-dragging-over'
  //         state.closestEdge = closestEdge
  //       },
  //       onDragLeave() {
  //         state.type = 'idle'
  //       },
  //       onDrop() {
  //         state.type = 'idle'
  //       },
  //     }),
  // )



  // columnRefs.value.forEach((columnRef) => {
  //   if (columnRef) {
  //     combine(
  //         draggable({
  //           element: columnRef,
  //           getInitialData() {
  //             // 返回列的数据，用于拖拽时的识别
  //             const column = columnList.value.find((col) => col.id === columnRef.getAttribute('data-column-id'));
  //             return { ...column };
  //           },
  //         }),
  //         dropTargetForElements({
  //           element: columnRef,
  //           canDrop({ source }) {
  //             // 判断是否可以放置
  //             return source.element !== columnRef; // 禁止放置到自身
  //           },
  //           getData({ input }) {
  //             // 获取拖拽的数据
  //             const column = columnList.value.find((col) => col.id === columnRef.getAttribute('data-column-id'));
  //             return { ...column };
  //           },
  //           // ...其他事件处理函数
  //         }),
  //     );
  //   }
  // });

  //   //列表的拖拽
  //   const element = columnRef.value
  //   if (!element)
  //     return
  //   combine(
  //       draggable({
  //         element,
  //         getInitialData() {
  //           // return getTaskData(props.task)
  //           return props.task
  //         },
  //       }),
  //       dropTargetForElements({
  //         element,
  //         canDrop({ source }) {
  //           if (source.element === element) {
  //             return false
  //           }
  //           return true
  //         },
  //         getData({ input }) {
  //           // const data = getTaskData(props.task)
  //           const data = props.task
  //           return attachClosestEdge(data, {
  //             element,
  //             input,
  //             allowedEdges: ['top', 'bottom'],
  //           })
  //         },
  //         getIsSticky() {
  //           return true
  //         },
  //         onDragEnter({ self }) {
  //           const closestEdge = extractClosestEdge(self.data)
  //           state.type = 'is-dragging-over'
  //           state.closestEdge = closestEdge
  //         },
  //         onDrag({ self }) {
  //           const closestEdge = extractClosestEdge(self.data)
  //           if (state.type === 'is-dragging-over' && state.closestEdge === closestEdge) {
  //             return
  //           }
  //           state.type = 'is-dragging-over'
  //           state.closestEdge = closestEdge
  //         },
  //         onDragLeave() {
  //           state.type = 'idle'
  //         },
  //         onDrop() {
  //           state.type = 'idle'
  //         },
  //       }),
  //   )
  // 列表的拖拽完成
  unsubscribe = setupDragAndDrop()
  getProject() // 请求项目信息
  getColumnList()
  getTaskList() // 请求任务列表
})

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe()
  }
})

function tasksForColumn(columnId) {
  // console.log(`tasksForColumn columnId ${columnId}`)
  const filteredTasks = tasks.value.filter(task => task.columnId === columnId)
  // console.log(filteredTasks)
  return filteredTasks
}

const renderLabel: SelectRenderLabel = (option) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center',
      },
    },
    [
      h(NAvatar, {
        size: 'small',
        style: {
          color: 'white',
          backgroundColor: '#0556ec',
        },
        round: true
      }, {
        default: () => {
          return option.username
        },
      }),
      h(
        'div',
        {
          style: {
            marginLeft: '12px',
            padding: '4px 0',
          },
        },
        [
          h('div', null, [option.name as string]),
          h(
            NText,
            { depth: 3, tag: 'div' },
            [option.username as string],
            // {
            // default: () => 'description',
            // },
          ),
        ],
      ),
    ],
  )
}

const renderMultipleSelectTag: SelectRenderTag = ({
  option,
  handleClose,
}) => {
  return h(
    NTag,
    {
      style: {
        padding: '0 6px 0 4px',
      },
      round: true,
      closable: true,
      onClose: (e) => {
        e.stopPropagation()
        handleClose()
      },
    },
    {
      default: () =>
        h(
          'div',
          {
            style: {
              display: 'flex',
              alignItems: 'center',
            },
          },
          [
            h(NAvatar, {
              round: true,
              size: 22,
              style: {
                marginRight: '4px',
                color: 'white',
                backgroundColor: '#0556ec',
              },
              default: () => option.username
            }),
            option.username as string,
            // option.name && option.name.length > 2
            //     ? option.name.substr(0, 2).toUpperCase()
            //     : '未知' as string,
          ],
        ),
    },
  )
}

function showAddTaskModal(column) {
  selectColumn.value = column
  showModal.value = true
}

// 保存项目成员管理
async function saveUserManager() {
  console.warn('checkProjectUsers value--->', checkProjectUsers.value.join(','))
  const { data } = await api.updateProjectUser(useProject.value.id, checkProjectUsers.value.join(','))
  console.log(`保存项目成功返回-->${data}`)
  console.log(data)
  $message.success('成员管理修改成功')
  showUserManager.value = false
  // TODO 刷新成员管理
}
</script>

<style>
.title-box {
  display: flex;
  box-sizing: border-box;
  -webkit-box-align: center;
  align-items: center;
  flex-direction: row;
  -webkit-box-pack: justify;
  justify-content: space-between;
  padding-inline-start: 16px;
  padding-inline-end: 16px;
  padding-block-start: 8px;
  color: #7a869a;
  user-select: none;
  border-color: #e5e7eb;
  border-style: solid;
  border-width: 0;
}

.title-box span {
  letter-spacing: normal;
  margin-block: 0;
  text-transform: none;
  font:
    normal 600 12px / 16px ui-sans-serif,
    -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Ubuntu,
    system-ui,
    'Helvetica Neue',
    sans-serif;
  color: #172b4d;
}

.list-box {
  //box-sizing: border-box;
  //appearance: none;
  //border: none;
  //height: 100%;
  //overflow-y: auto;
}

.main {
  background-color: white;
  width: 100vw;
  height: 100vh;
  display: flex;
}

.content {
  //height: 100%;
  width: 100%;
  //background-color: #4c86f9;
  //display: flex;
  //flex-direction: column;
  //align-items: center;
  //justify-content: center;
  //gap: 0.5rem;
  //height: 100%;
  //border-radius: 5px;
  //border: gainsboro 2px solid;
  //padding: 0.5rem;
  //width: 420px;
  //margin: auto;
  //margin-top: 10px;
}

.item {
  width: 250px;
  background-color: #f4f5f7;
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  //position: relative;
  border-radius: 12px;
  transition: background 350ms cubic-bezier(0.15, 1, 0.3, 1);
  //border: 1px solid gainsboro;
  //border-radius: 5px;
  //font-size: 0.875rem;
  //line-height: 1.25rem;
  //padding: 0.5rem;
  //margin-top: 10px;
  //margin-bottom: 10px;
  //width: 380px;
}

.item-list {
  max-height: calc(100vh - 140px); /* 设置一个最大高度，根据需要调整 */
  padding-left: 5px;
  padding-right: 5px;
  //overflow-y: auto; /* 允许垂直方向滚动 */
  //overflow-x: hidden; /* 隐藏水平滚动条 */
}

.add-card-box {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: center;
  font-weight: 500;
  color: #475569;
  padding-bottom: 1px;
  padding-right: 28px;
  padding-top: 10px;
}

:deep(.n-modal__action) {
  background-color: white !important;
}

.column-item {
  cursor: grab;
  transition: all 0.2s ease;
}

.column-item:active {
  cursor: grabbing;
  opacity: 0.8;
  transform: scale(1.02);
}

.column-item.dragging {
  opacity: 0.5;
  background-color: #f8fafc;
}

.column-item.drag-over {
  border: 2px dashed #4c86f9;
}

.column-item.drag-over {
  border: 2px dashed #4c86f9;
}
.title-box {
  display: flex;
  box-sizing: border-box;
  -webkit-box-align: center;
  align-items: center;
  flex-direction: row;
  -webkit-box-pack: justify;
  justify-content: space-between;
  padding-inline-start: 16px;
  padding-inline-end: 16px;
  padding-block-start: 8px;
  color: #7a869a;
  user-select: none;
  border-color: #e5e7eb;
  border-style: solid;
  border-width: 0;
}

.title-box span {
  letter-spacing: normal;
  margin-block: 0;
  text-transform: none;
  font:
    normal 600 12px / 16px ui-sans-serif,
    -apple-system,
    BlinkMacSystemFont,
    'Segoe UI',
    Ubuntu,
    system-ui,
    'Helvetica Neue',
    sans-serif;
  color: #172b4d;
}

.list-box {
  //box-sizing: border-box;
  //appearance: none;
  //border: none;
  //height: 100%;
  //overflow-y: auto;
}

.main {
  background-color: white;
  width: 100vw;
  height: 100vh;
  display: flex;
}

.content {
  //height: 100%;
  width: 100%;
  //background-color: #4c86f9;
  //display: flex;
  //flex-direction: column;
  //align-items: center;
  //justify-content: center;
  //gap: 0.5rem;
  //height: 100%;
  //border-radius: 5px;
  //border: gainsboro 2px solid;
  //padding: 0.5rem;
  //width: 420px;
  //margin: auto;
  //margin-top: 10px;
}

.item {
  width: 250px;
  background-color: #f4f5f7;
  flex-direction: column;
  display: flex;
  box-sizing: border-box;
  //position: relative;
  border-radius: 12px;
  transition: background 350ms cubic-bezier(0.15, 1, 0.3, 1);
  //border: 1px solid gainsboro;
  //border-radius: 5px;
  //font-size: 0.875rem;
  //line-height: 1.25rem;
  //padding: 0.5rem;
  //margin-top: 10px;
  //margin-bottom: 10px;
  //width: 380px;
}

.item-list {
  max-height: calc(100vh - 140px); /* 设置一个最大高度，根据需要调整 */
  padding-left: 5px;
  padding-right: 5px;
  //overflow-y: auto; /* 允许垂直方向滚动 */
  //overflow-x: hidden; /* 隐藏水平滚动条 */
}

.add-card-box {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: center;
  font-weight: 500;
  color: #475569;
  padding-bottom: 1px;
  padding-right: 28px;
  padding-top: 10px;
}

:deep(.n-modal__action) {
  background-color: white !important;
}

.panel-header-box {
  display: flex;
  flex-direction: row;
  width: 100%;
  align-items: center;
  padding-left: 10px;
  padding-right: 10px;
  //position: fixed;
  //top: 0;
  //left: 0;
  //z-index: 1000;
  //background-color: cadetblue; /* 背景颜色 */
  //box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影 */ /* 确保在最上层 */
}

.content-wrapper {
  //padding-left: 270px;
  height: calc(100vh - 120px);
  overflow: hidden; /* 防止出现滚动条 */
}

.list_content {
  display: flex;
  flex-direction: row;
  justify-content: stretch;
  overflow-x: auto;
  padding: 8px;
  gap: 8px;
  height: calc(100vh - 120px);
}

.list_content > * {
  margin-right: 10px; /* 为所有子元素设置右边距 */
}

.list_content > :last-child {
  margin-right: 0; /* 最后一个子元素没有右边距 */
}

.cascader-box {
  --n-border: 0px solid rgb(224, 224, 230);
}

.new-board-box {
  width: 250px;
  flex-shrink: 0;
}

.new-board-btn {
  color: #1e293b;
  font-weight: 500;
  background-color: #e9eef5;
  width: 100%;
  outline: 2px solid transparent;
  outline-offset: 2px;
  align-items: center;
  border-radius: 0.5rem;
  cursor: pointer;
  display: inline-flex;
  justify-content: center;
  letter-spacing: 0.025em;
  padding: 0.5rem 1.25rem;
  text-align: center;
  transition-duration: 0.2s;
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

.n-base-selection__border {
  //border: none !important;
}

.n-base-selection {
  //--n-border-active: none !important;
  //--n-border-focus: none !important;
  //--n-border-hover: none !important;
  //--n-box-shadow-active: none !important;
  //--n-box-shadow-focus: none !important;
}

.n-scrollbar-content {
  margin: 0 0 0 5px;
}

.n-divider:not(.n-divider--vertical) {
  margin-top: 12px;
  margin-bottom: 12px;
}
.n-modal {
  border-radius: 12px; /* 设置您想要的圆角大小 */
}
</style>
